<script setup>
import {defineProps, ref, onMounted} from 'vue';
import {listProductReturn} from '@/api/pointRecord/pointRecord.js';
import useUserStore from '@/store/modules/user';

const userStore = useUserStore();

const props = defineProps({
  order: {
    type: Object,
    required: true
  }
});

// 退货审核状态
const returnStatus = ref(null);
const returnInfo = ref(null);

onMounted(async () => {
  await checkReturnStatus();
});

// 查询退货审核状态
const checkReturnStatus = async () => {
  try {
    const exchangeId = props.order.id; // 订单ID作为exchangeId

    if (!exchangeId) {
      return;
    }

    const res = await listProductReturn({
      exchangeId: exchangeId
    });

    if (res && res.rows && res.rows.length > 0) {
      const returnRecord = res.rows[0];
      returnStatus.value = parseInt(returnRecord.status); // 确保状态为数字类型
      returnInfo.value = returnRecord;
    } else {
      returnStatus.value = null;
      returnInfo.value = null;
    }
  } catch (e) {
    console.error(`查询退货审核状态失败 - 订单ID: ${props.order.id}`, e);
    returnStatus.value = null;
    returnInfo.value = null;
  }
};

// 总价计算
const totalPrice = (goodsList) => {
  // 如果订单对象有totalPoints字段，直接使用
  if (props.order.totalPoints !== undefined) {
    return props.order.totalPoints;
  }

  // 否则使用原来的计算逻辑作为备用
  let price = 0;
  goodsList.forEach(val => {
    const itemPrice = parseInt(val.price, 10) || 0;
    const itemNumber = parseInt(val.number, 10) || 0;
    price += itemPrice * itemNumber;
  });
  return price;
};

// 获取退货状态文字 - 修正为只有3种状态
const getReturnStatusText = (status) => {
  const statusMap = {
    0: '退货正在审核',
    1: '退货审核通过',
    2: '退货审核拒绝'
  };
  return statusMap[status] || '未知状态';
};

// 获取退货状态颜色 - 修正为只有3种状态
const getReturnStatusColor = (status) => {
  const colorMap = {
    0: '#f29100', // 橙色 - 审核中
    1: '#19be6b', // 绿色 - 通过
    2: '#fa3534'  // 红色 - 拒绝
  };
  return colorMap[status] || '#909399';
};

const goToCancel = (orderId) => {
  uni.navigateTo({
    url: `/pages/order/cancelOrder?id=${orderId}`
  });
};

const goToReturn = (order) => {
  const orderData = encodeURIComponent(JSON.stringify(order));
  uni.navigateTo({
    url: `/pages/order/returnGoods?id=${order.id}&order=${orderData}`
  });
};

const goToExpress = (orderId) => {
  uni.navigateTo({
    url: `/pages/order/express?id=${orderId}`
  });
};
</script>

<template>
  <view class="order">
    <view class="top">
      <view class="left">
        <u-icon name="home" :size="30" color="rgb(94,94,94)"></u-icon>
        <view class="store">{{ order.store }}</view>
        <u-icon name="arrow-right" color="rgb(203,203,203)" :size="26"></u-icon>
      </view>
      <view class="right">{{ order.deal }}</view>
    </view>

    <view class="item" v-for="(item, index) in order.goodsList" :key="index">
      <view class="left">
        <image :src="item.goodsUrl" mode="aspectFill"></image>
      </view>
      <view class="content">
        <view class="title u-line-2">{{ item.title }}</view>
        <view class="type">{{ item.type }}</view>
        <view class="delivery-time">购买时间 {{ item.deliveryTime }}</view>
      </view>
      <view class="right">
        <view class="price">
          {{ item.price }} 积分
        </view>
        <view class="number">x{{ item.number }}</view>
      </view>
    </view>

    <view class="total">
      实付款:
      <text class="total-price">
        {{ totalPrice(order.goodsList) }} 积分
      </text>
    </view>

    <!-- 退货状态提示 - 修复显示逻辑 -->
    <view v-if="returnStatus !== null" class="return-status">
      <view class="status-main">
        <text :style="{ color: getReturnStatusColor(returnStatus) }">
          {{ getReturnStatusText(returnStatus) }}
        </text>
      </view>

      <!-- 显示退货原因 -->
      <view v-if="returnInfo && returnInfo.returnReason" class="return-detail">
        <text class="detail-label">退货原因：</text>
        <text class="detail-text">{{ returnInfo.returnReason }}</text>
      </view>

      <!-- 显示审核备注/拒绝原因 -->
      <view v-if="returnInfo && returnInfo.reviewRemark" class="return-detail">
        <text class="detail-label">{{ returnStatus === 2 ? '拒绝原因：' : '审核备注：' }}</text>
        <text class="detail-text">{{ returnInfo.reviewRemark }}</text>
      </view>

      <!-- 显示物流信息 - 只在审核通过时显示 -->
      <view v-if="returnStatus === 1 && returnInfo && returnInfo.logisticsCompany && returnInfo.logisticsNo"
            class="return-detail">
        <text class="detail-label">退货物流：</text>
        <text class="detail-text">{{ returnInfo.logisticsCompany }} {{ returnInfo.logisticsNo }}</text>
      </view>

      <!-- 显示申请时间 -->
      <view v-if="returnInfo && returnInfo.createdTime" class="return-detail">
        <text class="detail-label">申请时间：</text>
        <text class="detail-text">{{ returnInfo.createdTime }}</text>
      </view>
    </view>

    <view class="bottom">
      <view class="more">
        <u-icon name="more-dot-fill" color="rgb(203,203,203)"></u-icon>
      </view>

      <!-- 查看物流按钮 -->
      <view v-if="['已发货', '已完成'].includes(order.deal)"
            class="logistics btn"
            @click="goToExpress(order.id)">
        查看物流
      </view>

      <!-- 取消购买按钮 -->
      <view v-if="order.deal === '待发货' && returnStatus !== 0"
            class="btn"
            @click="goToCancel(order.id)">
        取消购买
      </view>

      <!-- 退货按钮 - 只在没有退货记录或审核拒绝时显示 -->
      <view v-if="['已发货', '已完成'].includes(order.deal) && (returnStatus === null || returnStatus === 2)"
            class="btn"
            @click="goToReturn(order)">
        {{ returnStatus === 2 ? '重新申请退货' : '退货' }}
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.order {
  width: 710rpx;
  background-color: #ffffff;
  margin: 20rpx auto;
  border-radius: 20rpx;
  box-sizing: border-box;
  padding: 20rpx;
  font-size: 28rpx;

  .top {
    display: flex;
    justify-content: space-between;

    .left {
      display: flex;
      align-items: center;

      .store {
        margin: 0 10rpx;
        font-size: 32rpx;
        font-weight: bold;
      }
    }

    .right {
      color: $u-warning-dark;
    }
  }

  .item {
    display: flex;
    margin: 20rpx 0 0;

    .left {
      margin-right: 20rpx;

      image {
        width: 200rpx;
        height: 200rpx;
        border-radius: 10rpx;
      }
    }

    .content {
      flex: 1;

      .title {
        font-size: 28rpx;
        line-height: 50rpx;
      }

      .type {
        margin: 10rpx 0;
        font-size: 24rpx;
        color: $u-tips-color;
      }

      .delivery-time {
        color: #e5d001;
        font-size: 24rpx;
      }
    }

    .right {
      margin-left: 10rpx;
      padding-top: 20rpx;
      text-align: right;

      .price {
        font-size: 28rpx;
      }

      .number {
        color: $u-tips-color;
        font-size: 24rpx;
      }
    }
  }

  .total {
    margin-top: 20rpx;
    text-align: right;
    font-size: 28rpx;

    .total-price {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }

  .return-status {
    margin-top: 20rpx;
    padding: 15rpx;
    background-color: #f8f9fa;
    border-radius: 8rpx;
    font-size: 26rpx;
    border-left: 6rpx solid #f29100;

    .status-main {
      display: flex;
      align-items: center;
      margin-bottom: 10rpx;

      .return-code {
        color: #666;
        margin-left: 10rpx;
        font-size: 24rpx;
      }
    }

    .return-detail {
      display: flex;
      margin-bottom: 8rpx;
      font-size: 24rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .detail-label {
        color: #666;
        min-width: 120rpx;
        flex-shrink: 0;
      }

      .detail-text {
        color: #333;
        flex: 1;
        word-break: break-all;
      }
    }
  }

  .bottom {
    display: flex;
    margin-top: 40rpx;
    padding: 0 10rpx;
    justify-content: flex-end;
    align-items: center;

    .btn {
      line-height: 52rpx;
      width: 160rpx;
      border-radius: 26rpx;
      border: 2rpx solid $u-border-color;
      font-size: 26rpx;
      text-align: center;
      color: $u-info-dark;
      margin-left: 20rpx;
    }

    .more {
      margin-right: auto;
    }
  }
}
</style>
